#!/bin/bash
set -e

source $(dirname $0)/version

ARCH=${ARCH:-"amd64"}
SYSTEM_CHART_REPO_DIR=build/system-charts
SYSTEM_CHART_DEFAULT_BRANCH=${SYSTEM_CHART_DEFAULT_BRANCH:-"dev-v2.6"}
CHART_REPO_DIR=build/charts
CHART_DEFAULT_BRANCH=${CHART_DEFAULT_BRANCH:-"dev-v2.6"}

cd $(dirname $0)/../package

../scripts/k3s-images.sh

../scripts/create-components-file.sh

cp ../bin/rancher.yaml ../bin/rancher-namespace.yaml ../bin/rancher ../bin/agent ../bin/data.json ../bin/k3s-airgap-images.tar .

IMAGE=${REPO}/rancher:${TAG}
AGENT_IMAGE=${REPO}/rancher-agent:${AGENT_TAG}
RUNTIME_IMAGE=${REPO}/rancher-runtime:${TAG}

if [ ${ARCH} == arm64 ]; then
    sed -i -e '$a\' -e 'ENV ETCD_UNSUPPORTED_ARCH=arm64' Dockerfile
fi

docker build --build-arg VERSION=${TAG} --build-arg ARCH=${ARCH} --build-arg IMAGE_REPO=${REPO} --build-arg SYSTEM_CHART_DEFAULT_BRANCH=${SYSTEM_CHART_DEFAULT_BRANCH} --build-arg CHART_DEFAULT_BRANCH=${CHART_DEFAULT_BRANCH} -t ${IMAGE} .

docker build --build-arg VERSION=${TAG} --build-arg ARCH=${ARCH} --build-arg RANCHER_TAG=${TAG} --build-arg RANCHER_REPO=${REPO} -t ${AGENT_IMAGE} -f Dockerfile.agent .
if [ "${ARCH}" == amd64 ]; then
    docker build -t ${RUNTIME_IMAGE} -f Dockerfile.runtime .
fi

mkdir -p ../dist
echo ${IMAGE} > ../dist/images
echo ${AGENT_IMAGE} >> ../dist/images
echo Built ${IMAGE} #${AGENT_IMAGE}
echo

cd ../bin

if [ ! -d build/system-charts ]; then
    mkdir -p build
    git clone --depth=1 --no-tags --branch $SYSTEM_CHART_DEFAULT_BRANCH https://github.com/rancher/system-charts $SYSTEM_CHART_REPO_DIR
fi

if [ ! -d $CHART_REPO_DIR ]; then
    INDEX_PATH=$CHART_REPO_DIR/index.yaml
    git clone --branch $CHART_DEFAULT_BRANCH https://github.com/rancher/charts $CHART_REPO_DIR

    # Get list of paths to tarballs of the latest version of each chart from Helm repo's index.yaml
    LATEST_TGZ_PATHS=$(yq r $INDEX_PATH "entries.*.[0].urls[0]")

    # Extract the tarballs in the list, skip extracting CRD charts
    for TGZ_PATH in $LATEST_TGZ_PATHS; do
        TGZ_REL_PATH=$CHART_REPO_DIR/$TGZ_PATH
        TGZ_EXTRACT_PATH=$(dirname $CHART_REPO_DIR/${TGZ_PATH##released/})
        if [[ $TGZ_PATH == *crd*.tgz ]]; then
            echo "Skipped CRD: $TGZ_REL_PATH"
        else
            echo "Extract: $TGZ_REL_PATH to $TGZ_EXTRACT_PATH"
            mkdir -p $TGZ_EXTRACT_PATH
            tar -xf $TGZ_REL_PATH -C $TGZ_EXTRACT_PATH
        fi
    done

    # Remove index to force building a virtual index like system charts
    rm -f $INDEX_PATH $CHART_REPO_DIR/assets/index.yaml
fi

TAG=$TAG REPO=${REPO} go run ../pkg/image/export/main.go $SYSTEM_CHART_REPO_DIR $CHART_REPO_DIR/assets $IMAGE $AGENT_IMAGE $RUNTIME_IMAGE

if [ ${ARCH} == amd64 ]; then
    # rancherd tarball
    rm -rf build/rancherd/bundle
    mkdir -p build/rancherd/bundle
    tar c -C ../cmd/rancherd/bundle . | tar x -C build/rancherd/bundle
    cp -vf rancherd build/rancherd/bundle/bin
    tar czf rancherd-${ARCH}.tar.gz -C build/rancherd/bundle .
fi
